
package com.project.base.reflect;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


public class ReflectTools {

    public static Map<String, Object> getField(Object model) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Map<String, Object> map = new HashMap<String, Object>();
        Method[] method = model.getClass().getDeclaredMethods();// 获取所有方法
        if (method != null && method.length > 0) {
            for (Method m : method) {
                if (m.getName() != null && m.getName().startsWith("get")
                        && m.getName().length() > 3) {
                    String field = m.getName().substring(3);
                    // 取方法名为get...的
                    Object o = m.invoke(model);

                    // 执行
                    if (o != null) {
                        // 判断执行结果
                        map.put(field.toLowerCase(), o);
                    }

                }
            }

        }

        return map;
    }

    /**
     * 获取类的成员变量
     *
     * @param object
     * @return
     */
    public static Map<String, String> getFieldsAndValues(Object object) {
        Map<String, String> map = new HashMap<String, String>();
        Field[] fields = object.getClass().getFields();
        for (Field field : fields) {
            try {
                map.put(field.getName(), (String) field.get(object));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}
